import { reactive, watch } from 'vue'
import { defineStore } from 'pinia'
import MapJSON from "@/utils/MapToJSON.js";
// import { parse, stringify } from 'zipson'


export const useCartStore = defineStore('cart', () => {

  const cartListName = 'cartList'
  //第一层是店铺id，第二层是商品id，第三层是商品信息
  const initValue = localStorage.getItem(cartListName)
  // console.log(initValue);
  const cartList = reactive((initValue && MapJSON.JSONToMap(initValue)) || new Map([[0, new Map([[0, { name: '商品1', price: 100, number: 1 }]])]]))
  console.log(cartList);
  //持久化 cartList
  watch(() => cartList, (newVal) => {
    console.log("==========watch==========");
    console.log(cartList);
    localStorage.setItem(cartListName, MapJSON.MapToJSON(newVal))
  }, {
    immediate: true,
    deep: true
  })

  //获取指定商品id的购物车信息
  const getCartList = (shopId, goodsId) => cartList.get(shopId)?.get(goodsId) || null

  //获取指定店铺的购物车信息
  const getShopCartList = (shopId) => {
    const cartValue = cartList.get(shopId)
    return cartValue ? Array.from(cartValue.values()) : []
  }
  //清空指定id店铺的购物车信息
  //将指定id店铺的购物车里的所有商品的number置为0
  const clearCart = (shopId) => {
    // cartList.set(shopId,cartList.get(shopId))
    cartList.get(shopId).forEach((value) => {
      value.number = 0
    })
  }

  //修改添加商品、商品数量
  const updateCartList = (shopId, goodsId, num) => {
    // // 获取指定商品的引用
    console.log("==========updateCartList============");
    console.log(num);
    const cart = cartList.get(shopId)?.get(goodsId)
    if (!cart) {
      return false
    }
    cartList.get(shopId).get(goodsId).number += num
    return true

  }
  //创建购物车
  const setCartList = (shopId, goodsId, product) => {
    console.log("==========setCartList==========");
    console.log("创建购物车" + shopId + ":" + goodsId);
    console.log(product);
    // cartList.set(shopId, new Map([[goodsId, product]]))
    const shopInfo = cartList.get(shopId)
    console.log(shopInfo);
    if (!shopInfo) {
      cartList.set(shopId, new Map([[goodsId, product]]))
    } else {
      shopInfo.set(goodsId, { ...product })
    }
    console.log(cartList.get(shopId).get(goodsId));
    console.log(cartList);
  }

  return { cartList, clearCart, getCartList, getShopCartList, updateCartList, setCartList }

},
  {
    persist: {
      enabled: false,
    }
  }
  // {
  //   persist: {
  //     enabled: true,
  //     serialize: {
  //       deserialize: (value) => MapJSON.JSONToMap(value), // 反序列化成Map类型
  //       serialize: (value) => MapJSON.MapToJSON(value),   // 序列化成JSON字符串
  //     }
  //   },
  // }
)
